package com.wy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wy.common.CustomException;
import com.wy.entity.Category;
import com.wy.entity.Dish;
import com.wy.entity.Setmeal;
import com.wy.mapper.CategoryMapper;
import com.wy.service.CategoryService;
import com.wy.service.DishService;
import com.wy.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    @Override
    public void remove(Long id) {
        // sql语句 select count(*) from dish where category_id = ? 如果count >0,则表明关联不为0
        // 根据id分类进行查询
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);
        int count1 = dishService.count(dishLambdaQueryWrapper);
        if (count1 > 0) {
            // 有关联的菜品,抛出异常
            throw new CustomException("当前分类下关联了菜品,不能删除");

        }

        // 查询当前分类是否关联套餐
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);
        int count2 = setmealService.count(setmealLambdaQueryWrapper);
        if (count2 > 0) {
            // 有关联的套餐,抛出异常
            throw new CustomException("当前分类下关联了套餐,不能删除");
        }
        // 正常删除
        super.removeById(id);
    }
}
